<template>
  <div class="login-panel">
    <div class="title drag">
      EasyChat
    </div>
    <div v-if="showLoading" class="loading-panel">
      <img src="../assets/img/IMG_6904.GIF" />
    </div>
    <div v-else class="login-form">
      <div class="error-msg">
        {{ errorMsg }}
      </div>
      <el-form ref="formDataRef" :model="formData" :rules="rules" label-width="0px" @submit.prevent>
        <el-form-item prop="email">
          <el-input
            v-model.trim="formData.email"
            size="large"
            placeholder="请输入邮箱"
            maxlength="30"
            clearable
            @focus="cleanVerify"
          >
            <template #prefix>
              <span class="iconfont icon-email"> </span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" prop="nickName">
          <el-input
            v-model.trim="formData.nickName"
            size="large"
            placeholder="请输入昵称"
            maxlength="15"
            clearable
            @focus="cleanVerify"
          >
            <template #prefix>
              <span class="iconfont icon-user-nick"> </span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model.trim="formData.password"
            size="large"
            show-password
            placeholder="请输入密码"
            clearable
            @focus="cleanVerify"
          >
            <template #prefix>
              <span class="iconfont icon-password"> </span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" prop="rePassword">
          <el-input
            v-model.trim="formData.rePassword"
            size="large"
            show-password
            placeholder="请再次输入密码"
            clearable
            @focus="cleanVerify"
          >
            <template #prefix>
              <span class="iconfont icon-password"> </span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="checkCode">
          <div class="check-code-panel">
            <el-input
              v-model.trim="formData.checkCode"
              size="large"
              placeholder="请输入验证码"
              clearable
              @focus="cleanVerify"
            >
              <template #prefix>
                <span class="iconfont icon-checkcode"> </span>
              </template>
            </el-input>
            <img :src="checkCodeUrl" class="check-code" @click="changeCheckCode" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="submit">
            {{ isLogin ? '登录' : '注册' }}
          </el-button>
        </el-form-item>
        <div class="bottom-link">
          <span class="a-link" @click="changeOpType">{{
            isLogin ? '没有账号？' : '已有帐号'
          }}</span>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick } from 'vue'
const { proxy } = getCurrentInstance()
import md5 from 'js-md5'
import { useUserInfoStore } from '@/stores/UserInfoStore'
const userInfoStore = useUserInfoStore()

import { useRouter } from 'vue-router'
const router = useRouter()

const formData = ref({})
const formDataRef = ref()
//element自带表单验证
// const rules = {
//   email: [{ required: true, message: '请输入邮箱' }],
//   password: [{ required: true, message: '请输入密码' }],
//   checkCode: [{ required: true, message: '请输入验证码' }],
//   nickName: [{ required: true, message: '请输入昵称' }],
//   rePassword: [{ required: true, message: '请再次输入密码' }]
// }
const isLogin = ref(true)
const changeOpType = () => {
  window.ipcRenderer.send('loginOrRegister', !isLogin.value)
  isLogin.value = !isLogin.value
  nextTick(() => {
    formDataRef.value.resetFields()
    formDataRef.value = {}
    cleanVerify()
    changeCheckCode()
  })
}
//获取验证码
const checkCodeUrl = ref(null)
const changeCheckCode = async () => {
  let result = await proxy.Request({
    url: proxy.Api.checkCode
  })
  if (!result) {
    return
  }
  checkCodeUrl.value = result.data.checkCode
  localStorage.setItem('checkCodeKey', result.data.checkCodeKey)
}
changeCheckCode()
//错误消息
const errorMsg = ref(null)
const showLoading = ref(false)
//提交按钮
const submit = async () => {
  cleanVerify()
  if (!checkValue('checkEmail', formData.value.email, '请输入正确的邮箱')) {
    return
  }
  if (!isLogin.value && !checkValue(null, formData.value.nickName, '请输入昵称')) {
    return
  }
  if (formData.value.password == undefined || formData.value.password == '') {
    errorMsg.value = '请输入密码'
    return
  } else if (
    !checkValue(
      'checkPassword',
      formData.value.password,
      '密码只能由8-18位数字、字母、特殊字符组成'
    )
  ) {
    return
  }
  if (!isLogin.value && formData.value.password != formData.value.rePassword) {
    if (formData.value.rePassword == undefined || formData.value.rePassword == '') {
      errorMsg.value = '请再次输入密码'
    } else {
      errorMsg.value = '两次输入的密码不一致'
    }
    return
  }
  if (!checkValue(null, formData.value.checkCode, '请输入验证码')) {
    return
  }
  //登录后的遮罩效果
  if (isLogin.value) {
    showLoading.value = true
  }
  let result = await proxy.Request({
    //校验完调用登录/注册接口
    url: isLogin.value ? proxy.Api.login : proxy.Api.register,
    showLoading: isLogin.value ? false : true,
    showError: false,
    params: {
      email: formData.value.email,
      password: isLogin.value ? md5(formData.value.password) : formData.value.password,
      checkCode: formData.value.checkCode,
      nickName: formData.value.nickName,
      checkCodeKey: localStorage.getItem('checkCodeKey')
    },
    errorCallback: (response) => {
      showLoading.value = false
      changeCheckCode()
      errorMsg.value = response.info
    }
  })
  if (!result) {
    return
  }
  if (isLogin.value) {
    //登录成功后将用户状态存储到pinia中
    userInfoStore.setInfo(result.data)
    localStorage.setItem('token', result.data.token)
    router.push('/main')

    //与主进程进行交互，进入主界面改变窗口大小
    const screenWidth = window.screen.width
    const screenHeight = window.screen.height
    window.ipcRenderer.send('openChat', {
      email: formData.value.email,
      token: result.data.token, //初始化ws时需要验证token，必须传过去
      userId: result.data.userId,
      nickName: result.data.nickName,
      admin: result.data.admin,
      screenWidth: screenWidth,
      screenHeight: screenHeight
    })
  } else {
    proxy.Message.success('注册成功')
    changeOpType()
  }
}
//抽离的校验函数
const checkValue = (type, value, msg) => {
  if (proxy.Utils.isEmpty(value)) {
    //抽离的工具Utils
    errorMsg.value = msg
    return false
  }
  if (type && !proxy.Verify[type](value)) {
    //抽离的工具Verify
    errorMsg.value = msg
    return false
  }
  return true
}
//清空校验
const cleanVerify = () => {
  errorMsg.value = null
}
</script>

<style lang="scss" scoped>
@import url('@/assets/style/login/login.scss');
</style>
